<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="总价" prop="totalPrice">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="房源名称" align="center" prop="property.name" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="签约合同" align="center" prop="contract">
        <template slot-scope="scope">
          <a :href="'/dev-api/profile/upload/' + processedContractLink(scope.row.contract)" target="_blank" style="color: #36d">{{ scope.row.orderUser }}的租房合同</a>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="craetTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.craetTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="租赁时长(月)" align="center" prop="duration" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="租客" align="center" prop="orderUser" />
      <el-table-column label="租客电话" align="center" prop="orderPhone" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row,scope.index)"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="租客名字" prop="orderUser">
          <el-input v-model="form.orderUser"  placeholder="请输入内容" />
        </el-form-item><el-form-item label="联系电话" prop="otherInfo">
          <el-input v-model="form.orderPhone" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="其他相关信息" prop="otherInfo">
          <el-input v-model="form.otherInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="租赁时长" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入租赁时长" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="propertyList" @row-click="handleRowClickD">
        <!-- 修改为单选模式 -->
        <el-table-column label="选择" width="55" align="center">
          <template slot-scope="scope">
            <el-radio v-model="selectedProperty" :label="scope.row" @change="handleRowClickD(scope.row)"></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="房源名称" align="center" prop="name" />
        <el-table-column label="地址" align="center" prop="address" />
        <el-table-column label="房东" align="center" prop="homeowner.userName" />
        <el-table-column label="户型" align="center" prop="layout">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_property_type" :value="scope.row.layout"/>
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="合同名称" align="center">
          <template slot-scope="scope">
            <a :href="'/dev-api' + scope.row.contract.file" target="_blank" style="color: #36d">{{ scope.row.contract.contractName }}</a>
          </template>
        </el-table-column>
        <el-table-column label="房源状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_property_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" prop="photo" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.photo" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="其他相关信息" align="center" prop="otherInfo" />
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getListProperty"
      />


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>


    </el-dialog>
    <!-- 订单详细 -->
    <el-dialog title="订单详细" :visible.sync="opens" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row v-if="form && form.property">
          <el-col :span="12">
            <el-form-item label="房源名称：">{{ form.property.name }} </el-form-item>
            <el-form-item
              label="房东信息："
            >{{ form.property.homeowner.userName }} | {{ form.property.homeowner.phonenumber }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称：">{{ form.property.contract.contractName }}</el-form-item>
            <el-form-item label="未签约合同：">
              <div class="file-bag">
                <i class="el-icon-folder"></i>
                <a :href="'/dev-api' + form.property.contract.file" target="_blank">{{ form.property.contract.contractName }}</a>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="房源月租：">{{ form.property.deposit }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="押金形式：">
              <div v-if="form.property.depositRule === 0">无押金</div>
              <div v-else-if="form.property.depositRule === 1">押一付一</div>
              <div v-else-if="form.property.depositRule === 3">押一付三</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="房源照片：">
              <image-preview :src="form.property.photo" alt="房源照片" :width="50" :height="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="房源信息：">{{  form.property.otherInfo }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="签约合同：">
              <div class="file-bag">
                <i class="el-icon-folder"></i>
                <a :href="'/dev-api' + form.contract" target="_blank">{{ form.property.contract.contractName }}</a>
              </div>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <el-form-item label="创建时间：">{{  parseTime(form.creatTime) }}</el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="租期：">{{  form.startTime }} ~ {{ form.endTime }} | {{ form.duration }} 个月 </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作状态：">
              <div v-if="form.status === 0">未支付</div>
              <div v-else-if="form.status === 1">已支付</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="opens = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order";
import {parseTime} from "@/utils/ruoyi";
import {listProperty} from "@/api/system/property";

export default {
  name: "Order",
  dicts: ['sys_order_status','sys_property_status', 'sys_deposit_rule', 'sys_property_type', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //日期范围
      dateRange: [],
      // 房源信息表格数据
      propertyList: [],
      property:  [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单详情表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      opens: false,

      selectedProperty: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        creatTime: null,
        startTime: null,
        totalPrice: null,
        orderUser: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderUser: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: "租赁时长不能为空", trigger: "blur" }
        ],

        orderPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询订单详情列表 */
    getList() {
      this.loading = true;
      listOrder(this.addDateRange(this.queryParams,this.dateRange)).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    processedContractLink(contractPath) {
      const lastSlashIndex = contractPath.lastIndexOf('/');
      return contractPath.substring(lastSlashIndex + 1);
    },
    // 房源单选框选中数据
    handleRowClickD(row) {
      // 在这里处理单选逻辑，如将选中的房源信息保存到某个变量中
      this.selectedProperty = row;
      console.log(this.selectedProperty)
    },

    /** 查询房源信息列表 */
  getListProperty() {
    this.loading = true;
    // Ensure queryParams is defined; if not, initialize it as an object
    if (!this.queryParams) {
      this.queryParams = {};
    }
    
    // Add a status filter to query parameters
    this.queryParams.status = 0;

    // Optionally, handle date ranges if part of the original functionality
    const queryParams = this.addDateRange(this.queryParams, this.dateRange);
    
    return listProperty(queryParams).then(response => {
      this.propertyList = response.rows;
      this.total = response.total;
      this.loading = false;
    }).catch(error => {
      console.error('Error fetching property list:', error);
      this.loading = false;
    });
  },

    // 取消按钮
    cancel() {
      this.open = false;
      this.getList();
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        status: null,
        contract: null,
        otherInfo: null,
        creatTime: null,
        duration: null,
        startTime: null,
        endTime: null,
        totalPrice: null,
        createBy: null,
        updateBy: null,
        orderUser: null,
        orderPhone: null,
        remark: null,
        property: {
          propertyId: null,
          propertyName: null,
          propertyType: null,
          propertyAddress: null,
          propertyArea: null,
          propertyPrice: null,
          propertyStatus: null,
          depositRule: null,
          photo: null,
          otherInfo: null,
          createBy: null,
          updateBy: null,
          remark: null,
          contract: {
            contractId: null,
            contractName: null,
          },
          homeowner:{
            userId: null,
            phonenumber: null,
            userName: null,
            email: null
          }
        }

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.opens = true;
      this.form = row;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单详情";
      this.getListProperty();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单详情";
      });
    },
    /** 提交按钮 */
submitForm() {
  this.$refs["form"].validate(valid => {
    if (valid) {
      this.form.property = this.selectedProperty; // 将选中的房源ID（propertyId）赋值给this.form.property
      console.log("this.form.property after assignment:", this.form.property); // 新增的console.log

      if (this.form.orderId != null) {
        updateOrder(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addOrder(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},

    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单详情编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
